package com.leectrl.server;

import com.leectrl.adapter.TCPServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TCPServer {
    private static final int port = 6789;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public void run() throws Exception{

        //NioEventLoopGroup是用来处理IO操作的多线程事件循环器
        bossGroup= new NioEventLoopGroup(1);  // 用来接收进来的连接
        workerGroup  = new NioEventLoopGroup();// 用来处理已经被接收的连接
        try{
            ServerBootstrap server =new ServerBootstrap();//是一个启动NIO服务的辅助启动类
            server.group(bossGroup,workerGroup )
                    .channel(NioServerSocketChannel.class)  // 这里告诉Channel如何接收新的连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 自定义处理类

                            ChannelPipeline pipeline=ch.pipeline();
                            pipeline.addLast(new TCPServerHandler());
                        }
                    });
            server.option(ChannelOption.SO_BACKLOG, 1024); // 设置tcp缓冲区
            server.option(ChannelOption.SO_SNDBUF, 32 * 1024); // 设置发送缓冲大小
            server.option(ChannelOption.SO_RCVBUF, 32 * 1024); // 这是接收缓冲大小
            server.option(ChannelOption.SO_KEEPALIVE, true); // 保持连接
            ChannelFuture f = server.bind(port).sync();// 绑定端口，开始接收进来的连接
            if(f.isSuccess()){
                System.out.println("TCP服务启动 成功---------------");
            }
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


}
